package com.fusion.core.file.blockstorage;

import com.fusion.core.comm.Packet;

import java.io.IOException;
import java.util.BitSet;

/**
 * @author SwethaShivakumar 
 * Project: fusion
 * Date: Mar 12, 2009
 * URL: http://fusionwiki.co.cc
 * Mail Me At: shiva@fusionproject.co.cc
 */
public class BlockMask extends BitSet {

	private static final long serialVersionUID = 1L;

	public BlockMask() {
    }

    public BlockMask(int nbits, boolean allSet) {
        super(nbits);
        if (allSet) set(0,nbits);
    }

    public void serializeTo(Packet p) {
        try {
            int nBits = length();
            int len = nBits/8;
            if (nBits % 8 != 0) len++;
            p.writeShort(len);
            for(int i=0;i<len;i++) {
                byte b = 0;
                for(int j=0;j<8;j++) if (get(i*8+j)) b |= 1 << j;
                p.writeByte(b);
            }
        } catch(Exception e) {
            throw new RuntimeException("Could not serialize BlockMask: "+e);
        }
    }

    public static BlockMask createFrom(Packet data) throws IOException {
        BlockMask bm = new BlockMask();
        int nbytes = data.readUnsignedShort();
        for(int i=0;i<nbytes;i++) {
            byte b = data.readByte();
            for(int j=0;j<8;j++) if ((b & (1 << j)) != 0) bm.set(i*8+j);
        }
        return bm;
    }
}
